#define _CRT_SECURE_NO_WARNINGS
#include"SeqList.h"

void SLInit(SL* ps)
{
	SLDataType* tmp = (SLDataType*)malloc(sizeof(SLDataType) * INIT_CAPACITY);
	if (tmp == NULL)
	{
		perror("malloc");
		exit(1);
	}
	ps->data = tmp;
	ps->size = 0;
	ps->capacity = INIT_CAPACITY;
}

void SLDestroy(SL* ps)
{
	free(ps->data);
	ps->data = NULL;
	ps->capacity = ps->size = 0;
}

void SLPrint(SL* ps)
{
	assert(ps);
	for (int i = 0; i < ps->size; i++)
	{
		printf("%d ", *(ps->data + i));
	}
}

void SLCheckCapacity(SL* ps)
{
	assert(ps);
	SLDataType* tmp = (SLDataType*)realloc(ps->data, sizeof(SLDataType) * 2 * (ps->capacity));
	if (tmp == NULL)
	{
		perror("realloc");
		exit(1);
	}
	ps->data = tmp;
	ps->capacity *= 2;
}


void SLPushBack(SL* ps, SLDataType x)
{
	assert(ps);
	if (ps->capacity == ps->size)
	{
		SLCheckCapacity(ps);
	}
	ps->data[ps->size++] = x;
}

void SLPushFront(SL* ps, SLDataType x)
{
	assert(ps);
	if (ps->size == ps->capacity)
	{
		SLCheckCapacity(ps);
	}
	for (int i = ps->size; i > 0; i--)
	{
		ps->data[i] = ps->data[i- 1];
	}
	ps->data[0] = x;
	ps->size++;
}

void SLPophBack(SL* ps)
{
	assert(ps);
	assert(ps->size);

	ps->size--;
}


void SLPophFront(SL* ps)
{
	assert(ps);
	assert(ps->size);

	for (int i = 0; i < ps->size-1; i++)
	{
		ps->data[i] = ps->data[i + 1];
	}
	ps->size--;
}

void SLInsert(SL* ps, int pos, SLDataType x)
{
	assert(ps);
	assert(ps - 1 >= 0);
	if (ps->size == ps->capacity)
		SLCheckCapacity(ps);
	if (ps->size < pos - 1)
		SLPushBack(ps, x);
	else
	{
		for (int i = ps->size; i > pos-1; i--)
		{
			ps->data[i] = ps->data[i - 1];
		}
		ps->data[pos - 1] = x;
		ps->size++;
	}
}

void SLErase(SL* ps, int pos)
{
	assert(ps);
	assert(pos - 1 < ps->size);
	assert(ps->size);
	for (int i = pos - 1; i < ps->size; i++)
	{
		ps->data[i] = ps->data[i + 1];
	}
	ps->size--;
}

int SLFind(SL* ps, SLDataType x)
{
	assert(ps);
	assert(ps->size);
	for (int i = 0; i < ps->size; i++)
	{
		if (ps->data[i] == x)
			return i;
	}
	return -1;
}


